import axios from "axios";
import http from "./httpRequest";
import store from '@/store/index'
let name  //expire
let key  //res.data.policy.dir+this.imgInfo.name
let policy  //policy
let OSSAccessKeyId  //accessid
let Signature   //signature
let aliUrl    //host+name
let imgFile
let imgUrl




//上传动作
const uploald = function (imgInfo){
    imgFile = imgInfo
    //获取 阿里云密钥,通过java程序
    http({
        url: 'third/oss/policy',
        method: 'get'
    }).then((res)=>{
        // console.log("阿里云OSS密钥",res)
        name = res.data.policy.expire
        key = res.data.policy.dir+Math.round(Math.random()*999999999+1)+imgFile.name
        policy = res.data.policy.policy
        OSSAccessKeyId = res.data.policy.accessid
        Signature = res.data.policy.signature
        imgUrl = res.data.policy.host+'/'+key
        // console.log(imgUrl)
        if (res!=null){
            let param = new FormData();
            param.append('name', name)
            param.append('key', key)
            param.append('policy', policy)
            param.append('OSSAccessKeyId', OSSAccessKeyId)
            param.append('Signature', Signature)
            param.append('file', imgInfo);
            axios.post('https://shop-wangxiang.oss-cn-chengdu.aliyuncs.com', param).then((res) => {
                //图片存放地址
                store.commit("uploaldFile",imgUrl)
                // console.log("图片上成功",res)
                name = null
                key = null
                policy = null
                OSSAccessKeyId = null
                Signature = null
                aliUrl = null
            }).catch((err) => {
                // console.log("图片上传异常",err)
                name = null
                key = null
                policy = null
                OSSAccessKeyId = null
                Signature = null
                aliUrl = null
            })
        }
    })

}

//导出
export default {uploald}
